package com.xiaogao.centerEdu.controller;


import com.xiaogao.centerEdu.entity.UcenterMember;
import com.xiaogao.commonUtils.JwtUtils;
import com.xiaogao.commonUtils.Result;
import com.xiaogao.centerEdu.entity.vo.LoginVo;
import com.xiaogao.centerEdu.entity.vo.RegisterVo;
import com.xiaogao.centerEdu.service.UcenterMemberService;
import com.xiaogao.serviceBase.utils.exceptionHandler.XiaoGaoException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author 小高
 * @since 2021-06-27
 */
@RestController
@RequestMapping("/centerEdu/member")
@Api(description = "登录注册管理")
//@CrossOrigin
public class MemberController {

    @Autowired
    private UcenterMemberService memberService;

    @ApiOperation(value = "会员登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        String token = memberService.login(loginVo);
        return Result.ok().data("token",token);
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("/register")
    public Result register(@RequestBody RegisterVo registerVo) {

        boolean flag = memberService.register(registerVo);
        if (flag){
            return Result.ok();
        }else{
            return Result.error().message("注册失败");
        }
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("/getLoginInfo")
    public Result getLoginInfo(HttpServletRequest request){
        try{
            // 调用jwt的工具类方法,根据request对象获取头信息,返回用户id
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            // 根据id查询用户信息
            UcenterMember memberInfo = memberService.getById(memberId);
            return Result.ok().data("item",memberInfo);
        }catch (Exception e){
            e.printStackTrace();
            throw new XiaoGaoException(20001,"error");
        }
    }

    // 根据用户id获取用户信息
    @PostMapping("/getInfo/{memberId}")
    public UcenterMember getInfo(@PathVariable("memberId")String memberId){
        // 根据用户id获取用户信息
        UcenterMember ucenterMember = memberService.getById(memberId);
        UcenterMember member = new UcenterMember();
        BeanUtils.copyProperties(ucenterMember,member);
        return member;
    }

    // 统计某一天注册人数
    @GetMapping("/registerCount/{day}")
    public Result registerCount(
            @PathVariable String day){
        Integer count = memberService.countRegisterByDay(day);
        return Result.ok().data("countRegister",count);
    }

}

